<template>
  <div>
    <el-row :gutter="20">
      <el-col
        :sm="24"
        :md="12"
        style="padding-bottom: 24px"
        v-for="(item, index) in content"
      >
        <el-card shadow="hover">
          <div class="content-wrapper">
            <div class="mode-code">
              <span>
                <el-icon><Promotion /></el-icon>
                <span style="padding-left: 12px">{{ item.code }}</span>
              </span>
              <span>
                <el-icon><DArrowRight /></el-icon>
                <span style="padding-left: 12px">{{ item.mode }}</span>
              </span>
            </div>
            <div class="computing-result">{{ item.capacity }}</div>
            <el-button link @click="handleConfig(index)">
              <span class="config-button">
                <el-icon>
                  <Operation />
                </el-icon>
              </span>
            </el-button>
          </div>
          <el-dialog
            v-model="configOpened"
            :title="`${configTarget ? configTarget.code : ''}机场参数设置`"
          >
            <div v-if="configTarget != null">
              <el-form label-width="80px">
                <span v-for="(rwy, index) in configTarget.runways">
                  <el-form-item
                    v-if="
                      rwy.available === 'departure' || rwy.available === 'both'
                    "
                    :label="`${rwy.code}离场`"
                  >
                    <div class="draggable-container">
                      <draggable
                        :list="configTarget.runways[index].departure"
                        item-key="id"
                        :animation="300"
                        :sort="true"
                        group="departure"
                        class="drag-area-departure"
                      >
                        <template #item="{ element }">
                          <span
                            class="draggable-element draggable-element-departure"
                          >
                            {{ element }}</span
                          >
                        </template>
                      </draggable>
                    </div>
                  </el-form-item>
                  <el-form-item
                    v-if="
                      rwy.available === 'arrival' || rwy.available === 'both'
                    "
                    :label="`${rwy.code}进场`"
                  >
                    <div class="draggable-container">
                      <draggable
                        :list="configTarget.runways[index].arrival"
                        item-key="id"
                        :animation="300"
                        :sort="true"
                        group="arrival"
                        class="drag-area-arrival"
                      >
                        <template #item="{ element }">
                          <span
                            class="draggable-element draggable-element-arrival"
                          >
                            {{ element }}</span
                          >
                        </template>
                      </draggable>
                    </div>
                  </el-form-item>
                </span>
              </el-form>
              <div
                style="
                  display: flex;
                  align-item: center;
                  justify-content: center;
                  padding-top: 12px;
                "
              >
                <el-button type="primary" @click="configOpened = false" link
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSave()">保存</el-button>
                <el-button type="primary" @click="handleSaveToAll()"
                  >保存并应用于全部时刻</el-button
                >
              </div>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import draggable from "vuedraggable";
// import airportData from "./airportData.json";

const props = defineProps({
  flowData: {
    type: Object,
    required: true,
  },
  presetContent: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["overide"]);

const content = ref([]);

const configTarget = ref(null);
const configOpened = ref(false);
let targetIndex = 0;

const handleConfig = (index) => {
  configTarget.value = JSON.parse(JSON.stringify(content.value[index]));
  configOpened.value = true;
  targetIndex = index;
};

const handleSave = () => {
  let direction = fetchDirection();
  if (!direction) {
    ElMessageBox({
      title: "出错了",
      message: "无法计算对头起降",
      type: "error",
    });
    return false;
  } else {
    let mode = fetchMode();
    let capacity = computeCapacity(mode);
    configTarget.value.capacity = capacity;
    configTarget.value.mode = mode.code;
    content.value[targetIndex] = configTarget.value;
    configOpened.value = false;
    return true;
  }
};

const handleSaveToAll = () => {
  if (handleSave()) {
    emits("overide", { value: configTarget.value, index: targetIndex });
  }
};

const fetchDirection = () => {
  let direction = "";
  for (let i = 0; i < configTarget.value.runways.length; i++) {
    let targetRunway = configTarget.value.runways[i];
    if (targetRunway.departure.length > 0 || targetRunway.arrival.length > 0) {
      if (direction == "" || direction == "both") {
        direction = targetRunway.direction;
      } else if (
        direction != targetRunway.direction &&
        targetRunway.direction != "both"
      ) {
        return null;
      }
    }
  }
  return direction;
};

const fetchMode = () => {
  let code = "";
  let departure = new Array();
  let arrival = new Array();
  for (let i = 0; i < configTarget.value.runways.length; i++) {
    let targetRunway = configTarget.value.runways[i];
    let letter = "";
    let inUse = false;
    if (targetRunway.departure.length > 0) {
      inUse = true;
      departure.push(targetRunway.code);
      if (targetRunway.available == "both") {
        letter = "D";
      }
    }
    if (targetRunway.arrival.length > 0) {
      inUse = true;
      arrival.push(targetRunway.code);
      if (targetRunway.available == "both") {
        if (letter == "") {
          letter = "A";
        } else {
          letter = "Q";
        }
      }
    }
    code += inUse ? targetRunway.code + letter : "";
  }
  return {
    code,
    departure,
    arrival,
  };
};

const computeCapacity = (mode) => {
  let capacity = 0;
  let basicCapacity = mode.arrival.length == 2 ? 20 : 30;
  for (let i = 0; i < configTarget.value.runways.length; i++) {
    let runwayCapacity = 0;
    let targetRunway = configTarget.value.runways[i];
    if (targetRunway.arrival.length > 0) {
      if (targetRunway.departure.length > 0) {
        // 跑道既用于起飞又用于落地
        let x = 0;
        let depObj =
          props.flowData.airport[configTarget.value.code].type.DEP.point;
        Object.keys(depObj).forEach((key) => {
          if (targetRunway.departure.indexOf(key) > -1) {
            // 基于流量信息计算跑道起飞数量
            console.log(
              "matched point",
              targetRunway.departure,
              key,
              depObj[key]
            );
            x += depObj[key];
          }
        });
        console.log(targetRunway.code, "X Value", x);
        if (mode.arrival.length == 1) {
          // 按照单落计算
          if (x < 5) {
            runwayCapacity = basicCapacity;
          } else if (x < 13) {
            runwayCapacity = basicCapacity - Math.round(x / 2);
          } else {
            runwayCapacity =
              basicCapacity - Math.round(x / 2) - Math.round((x - 13) / 2);
          }
        } else {
          // 按照双落计算
          if (x < 16) {
            runwayCapacity = basicCapacity;
          } else {
            runwayCapacity = basicCapacity - Math.round((x - 15) / 2);
          }
        }
      } else {
        // 跑道只用于落地
        runwayCapacity = basicCapacity;
      }
    }
    console.log(targetRunway.code, "runwayCapacity", runwayCapacity);
    capacity += runwayCapacity;
  }
  console.log(
    configTarget.value.code,
    props.flowData.moment,
    "capacity",
    capacity
  );
  return capacity;
};

onMounted(() => {
  content.value = JSON.parse(JSON.stringify(props.presetContent));
  // if (props.presetContent) {
  //   content.value = JSON.parse(JSON.stringify(props.presetContent));
  // } else {
  //   content.value = JSON.parse(JSON.stringify(airportData));
  // }
  for (let i = 0; i < content.value.length; i++) {
    configTarget.value = JSON.parse(JSON.stringify(content.value[i]));
    targetIndex = i;
    handleSave();
  }
});
</script>

<style scoped>
.content-wrapper {
  display: flex;
  /* flex-direction: column; */
  align-items: center;
  justify-content: space-between;
}
.computing-result {
  font-size: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 3;
  /* width: 120px; */
}
.mode-code {
  font-size: 18px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  flex: 2;
  /* width: 120px; */
}

.mode-code > span {
  padding: 4px 0;
}
.config-button {
  font-size: 36px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  /* width: 120px; */
}

.draggable-container {
  min-height: 36px;
  min-width: 100%;
  border: 1px solid rgba(128, 128, 128, 0.5);
  border-radius: 8px;
}

.drag-area-arrival,
.drag-area-departure {
  min-width: 100%;
  min-height: 36px;
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  align-items: center;
}

.draggable-element {
  margin: 4px;
  border-radius: 4px;
  font-size: 14px;
  color: #fff;
  user-select: none;
  cursor: pointer;
  width: 64px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "Consolas", monospace;
  border: 2px solid #fff;
  transition: all 0.3s ease-in-out;
}

.draggable-element-departure {
  background-color: rgba(64, 168, 96, 0.75);
  border-color: rgba(64, 168, 96, 1);
}

.draggable-element-departure:hover {
  background-color: rgba(64, 168, 96, 1);
}

.draggable-element-arrival {
  background-color: rgba(255, 75, 0, 0.75);
  border-color: rgba(255, 75, 0, 1);
}

.draggable-element-arrival:hover {
  background-color: rgba(255, 75, 0, 1);
}
</style>
